import { Controller, UseFilters, UseInterceptors, UsePipes, ValidationPipe, UseGuards, Get, Param, HttpException, BadRequestException } from '@nestjs/common';
import { ApiTags, ApiBearerAuth, ApiOperation } from '@nestjs/swagger';
import { Crud, CrudController } from '@nestjsx/crud';
import { Funds } from 'libs/db/entity/funds.entity';
import { HttpExceptionFilter } from '../_filter/http-exception.filter';
import { LoggingInterceptor } from '../_interceptor/logging.interceptor';
import { FundsCrudOps } from './funds-crud-ops';
import { FundsService } from './funds.service';
import { AuthGuard } from '@nestjs/passport';
import { InjectRepository } from '@nestjs/typeorm';


@Crud(FundsCrudOps)
@UseFilters(HttpExceptionFilter)
@UsePipes(ValidationPipe)
@UseInterceptors(LoggingInterceptor)
@UseGuards(AuthGuard('jwt-admin'))
@ApiBearerAuth()
@ApiTags('三资管理 - 资金信息')   //标签
@Controller('funds')
export class FundsController implements CrudController<Funds> {
  constructor(
    public service: FundsService,
    @InjectRepository(Funds) private readonly fundsRepo,
  ) {
  }

  @ApiOperation({
    description: '日期参考 2010-10 2010',
    summary: '根据日期查询以镇为单位的月或年总收入, 总支出',
  })
  @Get('date/:date')
  async getFundsForMonth (@Param('date') date: string) {
    const dateYearRege = /^[0-9]{4}$/
    const dateMonthRege = /^[0-9]{4}$-^[0-9]{2}$/
    if(!(dateYearRege.test(date) || dateMonthRege.test(date))) {
      throw new BadRequestException(`日期参数错误, 参考 2010-10 2010`)
    } else {
      return await this.fundsRepo
              .query(
                  `SELECT
                    \`Town\`.\`id\` AS \`Town_id\`,
                    \`Town\`.\`name\` AS \`Town_name\`,
                    SUM(\`funds\`.\`input\`) AS input,
                    SUM(\`funds\`.\`output\`) AS output
                  FROM
                    \`town\` \`Town\`
                    LEFT JOIN \`village\` \`village\` ON \`village\`.\`townId\` = \`Town\`.\`id\`
                    LEFT JOIN \`funds\` \`funds\` ON \`funds\`.\`villageId\` = \`village\`.\`id\` 
                  WHERE
                    \`funds\`.\`time\` LIKE '${date}%' AND
                    \`Town\`.\`deleteAt\` IS NULL AND
                    \`village\`.\`deleteAt\` IS NULL AND
                    \`funds\`.\`deleteAt\` IS NULL 
                  GROUP BY(\`Town\`.\`id\`)`
            );
    }
  }
}
